package com.bj58.analysis.tools;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;


import com.bj58.analysis.tools.common.bean.LogBean;

/**
 * @description 对单条日志进行解析
 * @author tzc
 *
 */
public class CommonAnalysisToolsDriver {
	private static Map<LogToolsTag, CommonAnalysis> maps = null;// 用于标识变换日志类型的解析

	/**
	 * @description 将日志解析成json格式
	 * @param logLine
	 *            日志
	 * @param logTag
	 *            日志类型标记
	 * @return 返回json格式的，如果是错误日志，无法正确解析，则返回null
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static String parserToJoson(String logLine, LogToolsTag toolTag)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		if (maps == null)// 懒加载
			maps = new HashMap<LogToolsTag, CommonAnalysis>();

		String log = null;
		String flag = toolTag.getTag();
		CommonAnalysis tool = maps.get(toolTag);
		if (tool == null) {
			Class<?> claz = Class.forName(flag);
			tool = (CommonAnalysis) claz.newInstance();
			maps.put(toolTag, tool);
		}

		LogBean bean = tool.analysis(logLine);
		if (bean != null)
			log = JSONObject.fromObject(bean).toString();
		
		return log;
	}

	/**
	 * @description 将日志解析成为一个对象
	 * @param logLine
	 *            日志
	 * @param logTag
	 *            日志类型标记
	 * @return 将日志解析封装成一个对象返回，如果无法正确解析将返回null
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static LogBean parserToInstance(String logLine, LogToolsTag toolTag)
			throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
		if (maps == null)// 懒加载
			maps = new HashMap<LogToolsTag, CommonAnalysis>();

		String flag = toolTag.getTag();
		CommonAnalysis tool = maps.get(toolTag);
		if (tool == null) {
			Class<?> claz = Class.forName(flag);
			tool = (CommonAnalysis) claz.newInstance();
			maps.put(toolTag, tool);
		}

		return tool.analysis(logLine);
	}

}
